package login

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"mz_water/entity"
	models "mz_water/model"
	"mz_water/util"
	"net/http"
	"os"
)

func Login(c *gin.Context) {
	var res = &entity.Result{}
	// 保存登录态
	p := util.Pool.Get()
	defer p.Close() //函数运行结束 ，把连接放回连接池
	code := c.PostForm("code")
	app, _ := GetSessionCode(code)
	// 判断是否使用过
	_, err := models.WxLogin(app)
	if err != nil {
		res.SetCode(201)
		c.JSON(http.StatusOK, res.SetData(err))
		return
	}
	//// 这里用openid和sessionkey的串接 进行MD5之后作为该用户的自定义登录态
	MySession := app.Openid + "|" + app.Session_key
	_, err = p.Do("sadd", "wx_session", MySession)
	if err != nil {
		fmt.Println(err)
		return
	}
	res.SetCode(200)
	res.SetData(MySession)
	res.SetMessage("登录成功")
	c.JSON(http.StatusOK, res)
}

func GetSessionCode(code string) (app *entity.APPSECRET, err error) {
	// 小程序登录凭证
	APP_ID := os.Getenv("APP_ID")
	APP_SECRET := os.Getenv("APP_SECRET")
	query := "https://api.weixin.qq.com/sns/jscode2session?appid=" + APP_ID + "&secret=" + APP_SECRET + "&js_code=" + code + "&grant_type=authorization_code"
	resp, _ := http.Get(query)
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	apps := &entity.APPSECRET{}
	json.Unmarshal(body, &apps)
	return apps, err
}
